from ApiTestEngine.core2.cases import run_test
from django.shortcuts import render
from django_filters.rest_framework import FilterSet
from rest_framework.response import Response
from django_filters import rest_framework as filters

# Create your views here.


from rest_framework.viewsets import ModelViewSet, GenericViewSet

from Scenes.serializers import TestSceneRunSerializer
from Testproject.models import TestEnvModel
from .models import TestTask, TestRecord, TestReport
from .serializers import TestTaskSerializer, TestTaskSceneSerializer, TestReportSerializer, TestRecordSerializer
from rest_framework import permissions, mixins

from .tasks import run_test_task


class TestTaskView(ModelViewSet):
    queryset = TestTask.objects.all()
    serializer_class = TestTaskSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['project']

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = TestTaskSceneSerializer(instance)
        return Response(serializer.data)

    def run_task(self, request):
        # 获取参数
        env_id = request.data.get("env")
        task_id = request.data.get("task")
        if not env_id:
            return Response({"msg": "env参数不能为空"}, status=400)
        if not task_id:
            return Response({"msg": "task参数不能为空"}, status=400)
        # 组装env_config
        run_test_task.delay(env_id, task_id, request.user.username)
        return Response({"msg": "测试任务已经开始执行！"}, status=200)


class TestRecordFilter(FilterSet):
    project = filters.NumberFilter(field_name="task__project")

    class Meta:
        model = TestRecord
        fields = ['project', 'task']


class TestRecordView(mixins.ListModelMixin,
                     GenericViewSet):
    queryset = TestRecord.objects.all().order_by('-create_time')
    serializer_class = TestRecordSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_class = TestRecordFilter


class TestReportView(mixins.RetrieveModelMixin,
                     GenericViewSet):
    queryset = TestReport.objects.all()
    serializer_class = TestReportSerializer
    permission_classes = [permissions.IsAuthenticated]

    def retrieve(self, request, *args, **kwargs):
        # 获取传入的任务id
        record = TestRecord.objects.get(id=kwargs['pk'])
        report = TestReport.objects.get(record=record)
        serializer = self.get_serializer(report)
        return Response(serializer.data)
